package com.beta.cms.test.demo.spring.container.impl;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.beta.cms.test.demo.spring.container.BeanFactory;

public class ClassPathXmlApplicationContext implements BeanFactory {
	// 定义容器
	private Map<String, Object> beans = new HashMap<String, Object>();

	public ClassPathXmlApplicationContext() throws Exception, Exception {
		// 文档输入流流
		SAXReader reader = new SAXReader();
		// 获取xml文件
		// File file = new File("D://beans.xml");
		InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("spring/beans.xml");
		// 获取文档
		Document document = reader.read(in);
		// 获取文档的根节点
		Element root = document.getRootElement();
		// 获取根节点下所有属性和子元素集合
		@SuppressWarnings("unchecked")
		List<Element> childElements = root.elements();
		for (Element child : childElements) {
			String id = child.attributeValue("id");
			String clazz = child.attributeValue("class");
			Object o = Class.forName(clazz).newInstance();
			System.out.println("id= " + id + " class= " + clazz);
			beans.put(id, o);
			@SuppressWarnings("unchecked")
			List<Element> elementList = child.elements();
			if (elementList != null && elementList.size() != 0) {
				for (Element propertyElement : elementList) {
					String name = propertyElement.attributeValue("name");
					String bean = propertyElement.attributeValue("bean");
					Object beanObject = beans.get(bean);
					String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
					System.out.println("method name = " + methodName);
					// 根据方法名,参数类型,获得方法
					Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
					// 执行该Method.invoke方法的参数是执行这个方法的对象owner，和参数数组args
					m.invoke(o, beanObject);
				}
			}
		}
	}

	@Override
	public Object getBean(String id) {
		return beans.get(id);
	}
}
